package com.zsj.stack;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @Author zsj
 * @Version 1.0
 * @Date 2024/3/24 14:25
 * @Description 基于数组实现栈
 */
@SuppressWarnings("all")
public class ArrayStack<E>
        implements Stack<E>,
        Iterable<E>,
        Serializable {

    private int size;//栈顶指针

    private int capacity = Integer.MAX_VALUE - 1;

    private E[] arr;


    //初始化容量
    public ArrayStack(int capacity) {
        this.capacity = capacity;
        arr = (E[]) new Object[capacity];
    }

    //默认无参构造方法
    public ArrayStack() {
        arr = (E[]) new Object[capacity];
    }

    @Override
    public boolean push(E value) {
        if (isFull()) return false;
        arr[size++] = value;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()) return null;
        //要弹出
        E value = arr[--size];
        return value;
    }

    @Override
    public E peak() {
        if (isEmpty()) return null;
        return arr[size - 1];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = size - 1;

            @Override
            public boolean hasNext() {
                return p > 0;//确实这个更好
            }

            @Override
            public E next() {
                return arr[p--];
            }
        };
    }

    @Override
    public void forEach(Consumer<? super E> action) {
        Iterable.super.forEach(action);
    }

    @Override
    public Spliterator<E> spliterator() {
        return Iterable.super.spliterator();
    }

    public int size() {
        return this.size;
    }
}
